'''
Created on 2011-5-9

@author: sevear
'''
import httplib, urllib;
import json;
import re;

SEARCH_URL = "www.xiami.com:80";

def searchSong(songName,album,artist,year=0,length=0,tryTime=0):
    params = urllib.urlencode({'key': songName});
        
    conn = httplib.HTTPConnection(SEARCH_URL);
    headers = {"Content-type": "application/x-www-form-urlencoded",
                "Accept": "text/json"}
    conn.request("POST","/app/iphone/search" , params,headers);
    response = conn.getresponse();
    data = str(response.read());
    conn.close();
    if(data!=None and data!=""):
        rstObj = json.loads(data);
    if(len(rstObj["songs"])>0):
        hitSong = chooseFitSong(rstObj["songs"],songName,album,artist);
    else:
        #try another way
        reexp = re.compile("[' ]+")
        cSongName = songName.lower();
        cSongName = re.sub(reexp," ", cSongName);
        kre = re.compile("\(.[^\(]*\)");
        cSongName = re.sub(kre,"",cSongName);
        hitSong = searchSongWithArtist(cSongName, album, artist, year, length);
    
    if(hitSong!=None):
            return hitSong["location"];
    else:
        reexp = re.compile("[' ]+")
        cSongName = songName.lower();
        cSongName = re.sub(reexp," ", cSongName);
        kre = re.compile("\(.[^\(]*\)");
        cSongName = re.sub(kre,"",cSongName);
        hitSong = searchSongWithArtist(cSongName, album, artist, year, length);
        
    if(hitSong!=None):
            return hitSong["location"];
    else:
        return "";
            
def searchSongWithArtist(songName,album,artist,year=0,length=0):
    params = urllib.urlencode({'key': songName+"+"+artist.lower()});
    conn = httplib.HTTPConnection(SEARCH_URL);
    headers = {"Content-type": "application/x-www-form-urlencoded",
                "Accept": "text/json"}
    conn.request("POST","/app/iphone/search" , params,headers);
    response = conn.getresponse();
    data = str(response.read());
    conn.close();
    if(data!=None and data!=""):
        rstObj = json.loads(data);
    if(len(rstObj["songs"])>0):
        return chooseFitSong(rstObj["songs"],songName,album,artist);

def chooseFitSong(songs,songName,album,artist,year=0,lenght=0):
    highgestP=0;
    highestSongs=[];
    hightestSong = None;
    
    rSongName = songName.lower();
    reexp = re.compile("['()[] ]+")
    rSongName = re.sub(reexp," ", rSongName)
    for song in songs:
        point = 0;
        rstSongName = song["name"];
        if(rSongName.lower()==rSongName):
            point += 100;
        else:
            rstSongName =  re.sub(reexp," ", rstSongName.lower());
            if(rSongName == rstSongName):
                point += 100;
        rstArtist = song["artist_name"];
        if(rstArtist.lower() == artist.lower() and point>0):
            point += 100;
        rstAlbum = song["title"];
        if(rstAlbum.lower() == album.lower() and point>0):
            point += 100;
        if(point>=highgestP and point>100):
            highgestP = point;
            highestSongs.append(song);
            hightestSong = song;
            
    return hightestSong;
